import React, { useState, useEffect } from 'react';
import DormitoryTable from './DormitoryTable';
import AddEditDormitoryModal from './AddEditDormitoryModal';
// 暂时注释，因为DormitoryDetailModal组件尚未实现
// import DormitoryDetailModal from './DormitoryDetailModal';
import ConfirmModal from '../teachers/components/ConfirmModal';
import Pagination from '../students/components/Pagination';
import { dataService } from '../../shared/dataService';
import { Dormitory, dormitoryTypeOptions, dormitoryStatusOptions, dataUtils } from '../../shared/models';
import { useContext } from 'react';
import { DataContext } from '../../shared/DataContext';
import './DormitoryPage.css';
import './AddEditDormitoryModal.css';

const DormitoryPage: React.FC = () => {
  const { addAuditLog } = useContext(DataContext);
  // 状态管理
  const [dormitories, setDormitories] = useState<Dormitory[]>([]);
  const [filteredDormitories, setFilteredDormitories] = useState<Dormitory[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [itemsPerPageOptions] = useState([10, 20, 50, 100]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedBuilding, setSelectedBuilding] = useState('');
  const [selectedType, setSelectedType] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  
  // 模态框状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 暂时注释，因为DormitoryDetailModal组件尚未实现
  // const [showDetailModal, setShowDetailModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [selectedDormitory, setSelectedDormitory] = useState<Dormitory | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  // 楼栋列表
  const [buildings, setBuildings] = useState<string[]>([]);

  // 获取宿舍数据
  const fetchDormitories = async () => {
    try {
      setLoading(true);
      const data = await dataService.getDormitories();
      setDormitories(data);
    } catch (error) {
      console.error('获取宿舍数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取所有独特的楼栋列表
  useEffect(() => {
    if (dormitories.length > 0) {
      const uniqueBuildings = [...new Set(dormitories.map(d => d.building))];
      setBuildings(uniqueBuildings.sort());
    }
  }, [dormitories]);

  // 初始化数据
  useEffect(() => {
    fetchDormitories();
  }, []);

  // 过滤宿舍数据
  useEffect(() => {
    let result = [...dormitories];

    // 按关键词搜索
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        dorm =>
          dorm.building.toLowerCase().includes(term) ||
          dorm.roomNumber.toLowerCase().includes(term) ||
          (dorm.supervisor && dorm.supervisor.toLowerCase().includes(term))
      );
    }

    // 按楼栋过滤
    if (selectedBuilding) {
      result = result.filter(dorm => dorm.building === selectedBuilding);
    }

    // 按类型过滤
    if (selectedType) {
      result = result.filter(dorm => dorm.type === selectedType);
    }

    // 按状态过滤
    if (selectedStatus) {
      result = result.filter(dorm => dorm.status === selectedStatus);
    }

    setFilteredDormitories(result);
    setCurrentPage(1); // 重置到第一页
  }, [dormitories, searchTerm, selectedBuilding, selectedType, selectedStatus]);

  // 分页逻辑
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentDormitories = filteredDormitories.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(filteredDormitories.length / itemsPerPage);

  // 处理每页显示条数变化
  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value, 10));
    setCurrentPage(1); // 重置到第一页
  };

  // 处理查看宿舍详情
  // 创建一个简单的handleViewDetail函数，避免运行时错误
  const handleViewDetail = (dormitory: Dormitory) => {
    console.log('查看宿舍详情:', dormitory);
    // 添加审计日志
    addAuditLog({
      action: 'view',
      entityType: 'dormitory',
      entityId: dormitory.id,
      entityName: `${dormitory.building} ${dormitory.roomNumber}`,
      details: `查看宿舍详情: ${dormitory.building} ${dormitory.roomNumber}`
    });
  };

  // 处理添加宿舍
  const handleAddDormitory = () => {
    setSelectedDormitory(null);
    setIsEditing(false);
    setIsModalOpen(true);
  };

  // 处理编辑宿舍
  const handleEditDormitory = (dormitory: Dormitory) => {
    setSelectedDormitory(dormitory);
    setIsEditing(true);
    setIsModalOpen(true);
  };

  // 处理删除宿舍
  const handleDeleteDormitory = (dormitory: Dormitory) => {
    setSelectedDormitory(dormitory);
    setShowConfirmModal(true);
  };

  // 处理关闭模态框
  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedDormitory(null);
  };

  // 确认删除宿舍
  const confirmDeleteDormitory = async () => {
    try {
      if (selectedIds.size > 0) {
        // 批量删除
        for (const id of selectedIds) {
          await dataService.deleteDormitory(id);
        }
        // 更新数据
        setDormitories(prev => prev.filter(d => !selectedIds.has(d.id)));
        // 清空选中状态
        setSelectedIds(new Set());
      } else if (selectedDormitory) {
        // 单个删除
        await dataService.deleteDormitory(selectedDormitory.id);
        // 更新数据
        setDormitories(prev => prev.filter(d => d.id !== selectedDormitory.id));
        // 添加审计日志
        addAuditLog({
          action: 'delete',
          entityType: 'dormitory',
          entityId: selectedDormitory.id,
          entityName: `${selectedDormitory.building} ${selectedDormitory.roomNumber}`,
          details: `删除宿舍: ${selectedDormitory.building} ${selectedDormitory.roomNumber}`
        });
      }
      // 重新获取楼栋列表
      fetchBuildings();
    } catch (error) {
      console.error('删除宿舍失败:', error);
    } finally {
      setShowConfirmModal(false);
    }
  };

  // 处理保存宿舍
  const handleSaveDormitory = async (dormitoryData: any) => {
    try {
      if (isEditing && selectedDormitory) {
        // 更新宿舍
        await dataService.updateDormitory(selectedDormitory.id, dormitoryData);
        // 更新本地数据
        setDormitories(prev => prev.map(d => 
          d.id === selectedDormitory.id ? { ...d, ...dormitoryData, updatedAt: new Date().toISOString() } : d
        ));
        // 添加审计日志
        addAuditLog({
          action: 'update',
          entityType: 'dormitory',
          entityId: selectedDormitory.id,
          entityName: `${selectedDormitory.building} ${selectedDormitory.roomNumber}`,
          details: `更新宿舍信息: ${selectedDormitory.building} ${selectedDormitory.roomNumber}`
        });
      } else {
        // 创建宿舍
        const newDormitory = await dataService.createDormitory({
          ...dormitoryData,
          currentOccupancy: 0, // 新建宿舍默认无人入住
        });
        // 添加到本地数据
        setDormitories(prev => [...prev, newDormitory]);
        // 添加审计日志
        addAuditLog({
          action: 'create',
          entityType: 'dormitory',
          entityId: newDormitory.id,
          entityName: `${newDormitory.building} ${newDormitory.roomNumber}`,
          details: `创建新宿舍: ${newDormitory.building} ${newDormitory.roomNumber}`
        });
      }
      // 重新获取楼栋列表
      fetchBuildings();
    } catch (error) {
      console.error('保存宿舍失败:', error);
    } finally {
      setIsModalOpen(false);
    }
  };

  // 处理选择行变化
  const handleSelectChange = (id: string, checked: boolean) => {
    const newSelectedIds = new Set(selectedIds);
    if (checked) {
      newSelectedIds.add(id);
    } else {
      newSelectedIds.delete(id);
    }
    setSelectedIds(newSelectedIds);
  };

  // 处理全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      const allIds = new Set(currentDormitories.map(d => d.id));
      setSelectedIds(allIds);
    } else {
      setSelectedIds(new Set());
    }
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedIds.size > 0) {
      setShowConfirmModal(true);
    }
  };

  return (
    <div className="dormitory-page">
      <div className="page-header">
        <h1>宿舍管理</h1>
        <div className="header-actions">
          <button className="btn-primary" onClick={handleAddDormitory}>
            添加宿舍
          </button>
          <button 
            className={`btn-danger ${selectedIds.size === 0 ? 'disabled' : ''}`}
            onClick={handleBatchDelete}
            disabled={selectedIds.size === 0}
          >
            批量删除 ({selectedIds.size})
          </button>
        </div>
      </div>

      <div className="filter-section">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索楼栋、房间号或管理员..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />
        </div>
        <div className="filter-controls">
          {/* 楼栋下拉菜单 */}
          <div className="enhanced-select-container">
            <select
              value={selectedBuilding}
              onChange={(e) => setSelectedBuilding(e.target.value)}
              className="filter-select"
            >
              <option value="">所有楼栋</option>
              {buildings.map(building => (
                <option key={building} value={building}>{building}</option>
              ))}
            </select>
            {selectedBuilding && (
              <button
                className="clear-btn"
                onClick={() => setSelectedBuilding('')}
                title="清除选择"
              >
                ×
              </button>
            )}
          </div>

          {/* 类型下拉菜单 */}
          <div className="enhanced-select-container">
            <select
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              className="filter-select"
            >
              <option value="">所有类型</option>
              {dormitoryTypeOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            {selectedType && (
              <button
                className="clear-btn"
                onClick={() => setSelectedType('')}
                title="清除选择"
              >
                ×
              </button>
            )}
          </div>

          {/* 状态下拉菜单 */}
          <div className="enhanced-select-container">
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="filter-select"
            >
              <option value="">所有状态</option>
              {dormitoryStatusOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            {selectedStatus && (
              <button
                className="clear-btn"
                onClick={() => setSelectedStatus('')}
                title="清除选择"
              >
                ×
              </button>
            )}
          </div>
          
          {/* 筛选结果统计 */}
          <div className="filter-summary">
            共 {filteredDormitories.length} 个宿舍
          </div>
        </div>
      </div>

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <>
          <DormitoryTable
          dormitories={currentDormitories}
          onEdit={handleEditDormitory}
          onDelete={handleDeleteDormitory}
          onViewDetail={handleViewDetail}
          selectedIds={selectedIds}
          onSelectChange={handleSelectChange}
          onSelectAll={handleSelectAll}
        />

          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalItems={filteredDormitories.length}
            itemsPerPage={itemsPerPage}
            onPageChange={setCurrentPage}
            onItemsPerPageChange={handleItemsPerPageChange}
            itemsPerPageOptions={itemsPerPageOptions}
          />
        </>
      )}

      {/* 添加/编辑宿舍弹窗 */}
      {isModalOpen && (
        <AddEditDormitoryModal
          isOpen={isModalOpen}
          isEditing={isEditing}
          dormitory={selectedDormitory}
          buildings={buildings}
          onClose={handleCloseModal}
          onSave={handleSaveDormitory}
        />
      )}

      {/* 确认删除弹窗 */}
      {showConfirmModal && (
        <ConfirmModal
          isOpen={showConfirmModal}
          title="确认删除"
          message={selectedIds.size > 0 
            ? `确定要删除选中的${selectedIds.size}个宿舍吗？此操作不可撤销。`
            : selectedDormitory 
              ? `确定要删除宿舍"${selectedDormitory.building} ${selectedDormitory.roomNumber}"吗？此操作不可撤销。`
              : '确定要删除所选宿舍吗？'}
          onCancel={() => setShowConfirmModal(false)}
          onConfirm={confirmDeleteDormitory}
        />
      )}

      {/* 暂时注释，因为DormitoryDetailModal组件尚未实现 */}
  {/* {showDetailModal && selectedDormitory && (
        <DormitoryDetailModal
          dormitory={selectedDormitory}
          isOpen={showDetailModal}
          onClose={() => setShowDetailModal(false)}
        />
      )} */}
    </div>
  );
};

export default DormitoryPage;